// Copyright 2022 jeff.li. and/or its affiliates.

#include <../src/codegen/codegen_c_host.h>
#include <tbir/ir/function.h>
#include <tbir/ir/module.h>
#include <tbir/ir/prim_builtin.h>
#include <tbir/ir/prim_expr.h>
#include <tbir/runtime/container.h>
#include <tbir/runtime/logging.h>
#include <tbir/runtime/registry.h>
#include <iostream>

#include <gtest/gtest.h>

namespace tbir::ir {
    using namespace runtime;

    TEST(IR, Printer) {
        const auto *printer = ::tbir::runtime::FunctionRegistry::Get("ir.AsText");
        const auto *build_module = ::tbir::runtime::FunctionRegistry::Get("module.build.c");

        PrimExpr a(3);
        PrimExpr b(4);

        PrimAdd c(a, b);

        PrimMul d(c, a);

        Bool cond(true);

        PrimCall custom(d.dtype(), builtin::if_then_else(), {cond, d, c});

        Array<Stmt> seq_stmt;
        seq_stmt.push_back(Evaluate(custom));
        SeqStmt body(seq_stmt);
        Array<PrimVar> params{PrimVar("n", DataType::Bool())};
        PrimFunc func(params, {}, body, PrimType(DataType::Int(32)));

        String ir_text = (*printer)({func}).As<String>();
        std::cout << ir_text << std::endl;

        func = WithAttr(std::move(func), attr::kGlobalSymbol, StringRef("test_arith"));

        codegen::CodeGenCHost cg;
        cg.AddFunction(func);
        std::string code = cg.Finish();
        std::cout << code << std::endl;

        IRModule module = IRModule::FromExpr(func);
        ::tbir::runtime::Module m = (*build_module)({module}).As<Module>();
        std::cout << m->GetSource() << std::endl;
    }

}  // namespace tbir::ir
